<template>
  <div class="arpe-container">
    <!-- Header -->
    <div class="arpe-header">
      <div class="arpe-title">酸轧生产效率监控</div>
    </div>

    <!-- Main Content Area -->
    <div class="arpe-main-content">
      <!-- Top Row: SVG Area using NewCoilCard -->
      <NewCoilCard title="工艺流程 SVG" class="svg-card">
        <!-- Wrapper for positioning context -->
        <div class="svg-card-content-wrapper">
          <!-- ADDED: Alarm Banner -->
          <div v-if="hasDefect" class="alarm-banner">
            ⚠️ {{ alarmBannerMessage }}
          </div>

          <!-- SVG Container -->
          <!-- @ts-ignore -->
          <!-- <div ref="svgContainerRef" class="svg-container" v-html="svgContent"></div> -->
          <RollPosImage2280 r-group="5703/2280酸轧机组" svg-url="/rollPosImage/2280.svg" />

          <!-- Gauges -->
          <div id="gauge-entry" class="gauge-container gauge-entry"></div>
          <div id="gauge-process" class="gauge-container gauge-process"></div>
          <div id="gauge-skinpass" class="gauge-container gauge-skinpass"></div>
          <div id="gauge-welder" class="gauge-container gauge-welder"></div>

          <!-- Info Boxes -->
          <div class="info-inlet-looper-val semitransp_box">
            <p>出口活套</p>
            <p>{{ inletLooperPercent.toFixed(1) }} %</p>
          </div>
          <div class="info-inlet-looper-time semitransp_box">
            <p>跑空时间</p>
            <p>{{ inletLooperTime }}</p>
          </div>
          <div class="info-middle-looper-val semitransp_box">
            <p>工艺段套量</p>
            <p>{{ middleLooperPercent.toFixed(1) }} %</p>
          </div>
          <div class="info-middle-looper-time semitransp_box">
            <p>跑空时间</p>
            <p>{{ middleLooperTime }}</p>
          </div>
          <div class="info-export-looper-val semitransp_box">
            <p>入口活套</p>
            <p>{{ exportLooperPercent.toFixed(1) }} %</p>
          </div>
          <div class="info-export-looper-time semitransp_box">
            <p>跑空时间</p>
            <p>{{ exportLooperTime }}</p>
          </div>
          <div class="info-uncoiler1 semitransp_box">
            <p>#1开卷机剩余</p>
            <p>{{ numberFormat1(uncoiler1Length) }} m</p>
          </div>
          <div class="info-uncoiler2 semitransp_box">
            <p>#2开卷机剩余</p>
            <p>{{ numberFormat1(uncoiler2Length) }} m</p>
          </div>
          <div class="info-coiler semitransp_box">
            <p>卷取长度</p>
            <p>{{ numberFormat1(coilerLength) }} m</p>
          </div>
          <div class="info-thickness-deviation semitransp_box">
            <p>厚度偏差</p>
            <p>{{ numberFormat3(thicknessDeviation) }} mm</p>
          </div>
          <div class="info-mill-entry-speed semitransp_box">
            <p>轧机入口速度</p>
            <p>{{ numberFormat1(millEntrySpeed) }} mpm</p>
          </div>
          <div class="info-yibiao1 semitransp_box">
            <p>圆盘剪速度</p>
          </div>
          <div class="info-yibiao2 semitransp_box">
            <p>工艺段速度</p>
          </div>

          <!-- 新增: AI 设定速度卡片 -->
          <div class="ai-speed-box info-ai-entry-speed">
            <p>入口段AI设定速度</p>
            <p>{{ aiEntrySpeed.toFixed(1) }} mpm</p>
          </div>
          <div class="ai-speed-box info-ai-process-speed">
            <p>工艺段AI设定速度</p>
            <p>{{ aiProcessSpeed.toFixed(1) }} mpm</p>
          </div>
          <div class="ai-speed-box info-ai-exit-speed">
            <p>出口段AI设定速度</p>
            <p>{{ aiExitSpeed.toFixed(1) }} mpm</p>
          </div>

          <!-- 新增: 小时吨钢状态框 -->
          <div class="arpe-status-box hourly-output">
            <div class="arpe-status-box-label">小时吨钢</div>
            <div class="arpe-status-box-value">{{ hourlySteelOutput.toFixed(1) }}<span>t</span></div>
          </div>
          <div class="arpe-status-box realtime-hourly-output">
            <div class="arpe-status-box-label">实时小时吨钢</div>
            <div class="arpe-status-box-value">{{ realtimeHourlySteelOutput.toFixed(1) }}<span>t</span></div>
          </div>

          <!-- 新增: 产量完成率 -->
          <div class="production-completion-rate">
            <div class="completion-rate-value">{{ productionCompletionRate }}%</div>
            <div class="completion-rate-label">产量完成率</div>
          </div>

        </div>
      </NewCoilCard>

      <!-- Bottom Row: Grid for other cards -->
      <div class="arpe-bottom-grid">
        <!-- Column 1 (Left) - Contains Horizontal Split -->
        <div class="arpe-bottom-column">
          <div class="left-column-content-wrapper"> <!-- New wrapper for horizontal layout -->
            <!-- Key Parameters Section (Left side of left column) -->
            <NewCoilCard title="班组" class="chart-card">
              <div class="arpe-chart" ref="teamOperationChartRef"></div>
            </NewCoilCard>
            <!-- Placeholder Card (Right side of left column) -->
            <NewCoilCard title="纠偏状态" class="chart-card">
              <div class="arpe-chart" ref="deviationChartRef"></div>
            </NewCoilCard>
          </div>
        </div>

        <!-- Column 2 (Right) - Vertical Stack (Top: Horizontal Tables, Bottom: Chart) -->
        <div class="arpe-bottom-column">
          <!-- Restored Horizontal Container for Tables -->
          <div class="arpe-bottom-column-horizontal">
            <!-- 前几卷对比 Card -->
            <NewCoilCard title="前几卷对比" class="table-card">
              <div class="table-container">
                <!-- 前几卷对比 el-table -->
                <el-table :data="coilComparisonData" size="small" height="100%" :header-cell-style="tableHeaderStyle"
                  :cell-style="tableCellStyle" :border="false">
                  <el-table-column prop="coilId" label="卷号" width="60" />
                  <el-table-column prop="time" label="时间" width="80" />
                  <el-table-column prop="entryEfficiency" label="入口效率%" width="60" />
                  <el-table-column prop="processEfficiency" label="工艺效率%" width="60" />
                  <el-table-column prop="exitEfficiency" label="出口效率%" width="60" />
                  <el-table-column prop="abnormalReason" label="异常原因" width="90" show-overflow-tooltip />
                  <el-table-column prop="rewelds" label="重焊" width="40" />
                  <el-table-column prop="adjustments" label="班调" width="40" />
                  <el-table-column prop="stripBreaks" label="断带" width="40" />
                </el-table>
              </div>
            </NewCoilCard>
            <!-- 入口材料卷信息 Card -->
            <NewCoilCard title="入口材料卷信息" class="table-card">
              <div class="table-container">
                <!-- 入口材料卷信息 el-table -->
                <el-table :data="entranceMaterialData" size="small" height="100%" :header-cell-style="tableHeaderStyle"
                  :cell-style="tableCellStyle" :border="false">
                  <el-table-column prop="materialId" label="材料编号" width="120" />
                  <el-table-column prop="grade" label="材料等级" width="120" />
                  <el-table-column prop="yieldStrength" label="屈服强度" width="120" />
                  <el-table-column prop="entryThickness" label="入口厚度" width="120" />
                  <el-table-column prop="entryWidth" label="入口宽度" width="120" />
                  <el-table-column prop="exitThickness" label="出口厚度" width="120" />
                </el-table>
              </div>
            </NewCoilCard>
          </div>
          <!-- Looper Status Chart (Below Horizontal Tables) -->
          <NewCoilCard title="Looper 状态" class="chart-card">
            <div class="arpe-chart" ref="looperChartRef"></div>
          </NewCoilCard>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick, watch, shallowRef } from 'vue';
import * as echarts from 'echarts/core';
import { BarChart, GaugeChart } from 'echarts/charts';
import {
  TooltipComponent,
  GridComponent,
  LegendComponent,
  GraphicComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import type { EChartsOption } from 'echarts';
import NewCoilCard from '../../components/NewCoilCard/NewCoilCard.vue';
import tcmSvgContent from '../../assets/svgs/TCM2280.svg?raw';
import RollPosImage2280 from '/@/views/common/RollPosImage/2280RollPosImage.vue';
import axios from 'axios';

echarts.use([
  TooltipComponent,
  GridComponent,
  LegendComponent,
  GraphicComponent,
  BarChart,
  GaugeChart,
  CanvasRenderer
]);

// --- Types ---
interface PathSegment {
  id: string;
  originalElement: SVGPathElement;
  pathClone: SVGPathElement;
  length: number;
  cumulativeLength: number;
}

// --- API Data & Simulation State ---
const apiData = ref<any>(null);
const itemTagData = ref<any>(null);
const fetchDataIntervalId = ref<number | null>(null);
const zoneCoilMap = ref<{ [key: string]: string | null }>({});
const coilColorMap = ref<{ [key: string]: string }>({});
const animationColors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#FF5733', '#C70039', '#900C3F', '#581845'];
let nextColorIndex = 0;

// --- Component Refs ---
const svgContainerRef = ref<HTMLElement | null>(null);
const looperChartRef = ref<HTMLElement | null>(null);
const teamOperationChartRef = ref<HTMLElement | null>(null);
const deviationChartRef = ref<HTMLElement | null>(null);

// --- SVG Animation State ---
const svgContent = ref(tcmSvgContent);
const pathSegments = shallowRef<PathSegment[]>([]);
const totalPathLength = ref(0);
const hasDefect = ref(false);
const alarmBannerMessage = ref<string>('注意：当前模拟缺陷已激活');

// --- Data ---
const entrySpeed = ref<number>(0);
const processSpeed = ref<number>(0);
const skinpassSpeed = ref<number>(0);
const welderSpeed = ref<number>(0);
const inletLooperPercent = ref<number>(0);
const inletLooperTime = ref<string>("0 min");
const middleLooperPercent = ref<number>(0);
const middleLooperTime = ref<string>("0 min");
const exportLooperPercent = ref<number>(0);
const exportLooperTime = ref<string>("0 min");
const uncoiler1Length = ref<number>(0);
const uncoiler2Length = ref<number>(0);
const coilerLength = ref<number>(0);
const thicknessDeviation = ref<number>(0);
const millEntrySpeed = ref<number>(0);
const hourlySteelOutput = ref<number>(135.0);
const realtimeHourlySteelOutput = ref<number>(152.5);
const productionCompletionRate = ref<number>(88);

// AI设定速度 (占位符)
const aiEntrySpeed = ref<number>(125.5);
const aiProcessSpeed = ref<number>(180.0);
const aiExitSpeed = ref<number>(240.2);

// Looper Chart
const looperData = reactive({ entry: { actual: 0, standard: 80 }, middle: { actual: 0, standard: 60 }, exit: { actual: 0, standard: 90 } });

// 新增: 班组操作时间图表数据
const teamOperationData = reactive({
  categories: ['开卷', '换卷', '换辊'],
  seriesData: {
    切头: [25, 35, 18],
    等待: [15, 25, 12],
    焊接: [40, 50, 30],
    释放: [10, 15, 8]
  }
});

// 新增: 纠偏状态图表数据
const deviationData = reactive({
  categories: ['CPC1', 'CPC2', 'CPC3', 'CPC4', 'CPC5', 'CPC6', 'CPC7', 'CPC8', 'CPC9', 'CPC10', 'CPC11'],
  seriesData: {
    带钢位置: [15, 12, -20, -18, 30, 25, -10, -12, 45, 40, -5],
    油缸位置: [20, 18, -15, -12, 25, 22, -5, -8, 40, 35, 0],
    _stripPosNegative: [-15, -12, 20, 18, -30, -25, 10, 12, -45, -40, 5]
  },
  colors: ['#409EFF', '#F56C6C', '#A0CFFF']
});

// Coil Comparison Table
const coilComparisonData = reactive([
  { coilId: 'C001', time: '10:30:15', entryEfficiency: 95, processEfficiency: 98, exitEfficiency: 97, abnormalReason: '-', rewelds: 0, adjustments: 1, stripBreaks: 0 },
  { coilId: 'C002', time: '10:32:40', entryEfficiency: 88, processEfficiency: 92, exitEfficiency: 90, abnormalReason: '速度波动', rewelds: 1, adjustments: 0, stripBreaks: 0 },
  { coilId: 'C003', time: '10:35:05', entryEfficiency: 96, processEfficiency: 99, exitEfficiency: 98, abnormalReason: '-', rewelds: 0, adjustments: 0, stripBreaks: 0 },
  { coilId: 'C004', time: '10:37:30', entryEfficiency: 94, processEfficiency: 95, exitEfficiency: 93, abnormalReason: '-', rewelds: 0, adjustments: 2, stripBreaks: 0 },
  { coilId: 'C005', time: '10:39:55', entryEfficiency: 85, processEfficiency: 88, exitEfficiency: 86, abnormalReason: '张力不稳', rewelds: 0, adjustments: 1, stripBreaks: 1 },
]);

// Entrance Material Table
const entranceMaterialData = reactive([
  { materialId: 'D250444402T', grade: 'DC01-H', yieldStrength: 240.0, entryThickness: 4.5, entryWidth: 1250, exitThickness: 1.615 },
  { materialId: 'D250444407T', grade: 'DC01-H', yieldStrength: 240.0, entryThickness: 4.5, entryWidth: 1250, exitThickness: 1.615 },
  { materialId: 'D250444410T', grade: 'SPCC-SD', yieldStrength: 220.0, entryThickness: 4.0, entryWidth: 1200, exitThickness: 1.500 },
  { materialId: 'D250444411B', grade: 'DC04', yieldStrength: 180.0, entryThickness: 5.0, entryWidth: 1300, exitThickness: 1.805 },
]);

// --- Chart Instances ---
let looperChartInstance: echarts.ECharts | null = null;
let teamOperationChartInstance: echarts.ECharts | null = null;
let gaugeEntryInstance: echarts.ECharts | null = null;
let gaugeProcessInstance: echarts.ECharts | null = null;
let gaugeSkinpassInstance: echarts.ECharts | null = null;
let gaugeWelderInstance: echarts.ECharts | null = null;
let deviationChartInstance: echarts.ECharts | null = null;

// --- Table Styles ---
const tableHeaderStyle = {
  background: '#183272',
  color: '#b8e8ff',
  padding: '4px 0',
  textAlign: 'center' as const,
  fontWeight: 'normal' as const,
  fontSize: '12px',
  borderBottom: '1px solid #06279d'
};

const tableCellStyle = {
  padding: '4px 0',
  textAlign: 'center' as const,
  color: '#c0c4cc',
  fontSize: '12px',
  borderBottom: '1px solid #06279d',
  borderRight: '1px solid #06279d'
};

// --- Utility Functions ---
const numberFormat1 = (number: any): string => {
  return number == undefined ? '0' : String(Number(parseFloat(number).toFixed(0)));
};

const numberFormat3 = (number: any): string => {
  return number == undefined ? '0' : String(Number(parseFloat(number).toFixed(3)));
};

// --- Base Chart Options ---
const getBaseChartOption = (): EChartsOption => ({
  backgroundColor: 'transparent',
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' },
    backgroundColor: 'rgba(10, 25, 50, 0.8)',
    borderColor: '#3a71a8',
    textStyle: { color: '#c0d8ff' }
  },
  grid: {
    left: '5%',
    right: '8%',
    top: '25%',
    bottom: '5%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    axisLine: { lineStyle: { color: '#3a71a8' } },
    axisLabel: { color: '#c0d8ff', fontSize: 10 },
    axisTick: { show: false },
    splitLine: { show: false }
  },
  yAxis: {
    type: 'value',
    axisLine: { show: false, lineStyle: { color: '#3a71a8' } },
    axisLabel: { color: '#c0d8ff', fontSize: 10 },
    splitLine: { lineStyle: { color: '#3a71a8', type: 'dashed', opacity: 0.3 } },
    splitNumber: 3
  },
  textStyle: {
    color: '#c0d8ff'
  },
  legend: {
    textStyle: { color: '#c0d8ff', fontSize: 10 },
    top: '8%',
    itemWidth: 10,
    itemHeight: 10
  }
});

// --- Chart Update Functions ---
const updateTeamOperationChart = () => {
  if (!teamOperationChartInstance) return;

  const seriesNames = Object.keys(teamOperationData.seriesData);
  const series = seriesNames.map(name => ({
    name: name,
    type: 'bar' as const,
    data: teamOperationData.seriesData[name as keyof typeof teamOperationData.seriesData],
    label: {
      show: true,
      position: 'right' as 'right',
      color: '#ffffff',
      fontSize: 10,
      formatter: '{c}'
    }
  }));

  const option: EChartsOption = {
    ...getBaseChartOption(),
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: seriesNames,
      top: '5%',
      textStyle: { color: '#ffffff' }
    },
    grid: {
      left: '3%',
      right: '10%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
      axisLabel: { color: '#c0d8ff', fontSize: 10 },
      splitLine: { show: true, lineStyle: { color: '#3a71a8', type: 'dashed', opacity: 0.2 } }
    },
    yAxis: {
      type: 'category',
      data: teamOperationData.categories,
      axisLine: { lineStyle: { color: '#3a71a8' } },
      axisLabel: { color: '#c0d8ff', fontSize: 11 },
      axisTick: { show: false }
    },
    series: series
  };

  teamOperationChartInstance.setOption(option, { notMerge: true });
};

// 新增: 纠偏状态图表初始化函数
const initDeviationChart = () => {
  if (!deviationChartRef.value) return;
  deviationChartInstance = echarts.init(deviationChartRef.value);

  const seriesNames = Object.keys(deviationData.seriesData);
  const legendData = seriesNames.filter(name => !name.startsWith('_'));

  const series = seriesNames.map((name, index) => ({
    name: name,
    type: 'bar' as const,
    data: deviationData.seriesData[name as keyof typeof deviationData.seriesData],
    itemStyle: {
      color: deviationData.colors[index % deviationData.colors.length]
    },
    label: {
    },
    barWidth: '25%',
    legendHoverLink: !name.startsWith('_')
  }));

  const option: EChartsOption = {
    ...getBaseChartOption(),
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: legendData,
      top: '5%',
      textStyle: { color: '#ffffff' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: { color: '#c0d8ff', fontSize: 10 },
      splitLine: { show: true, lineStyle: { color: '#3a71a8', type: 'dashed', opacity: 0.2 } }
    },
    yAxis: {
      type: 'category',
      data: deviationData.categories,
      axisLine: { lineStyle: { color: '#3a71a8' } },
      axisLabel: {
        color: '#c0d8ff',
        fontSize: 11,
        formatter: (value: string, index: number) => {
          return index % 2 === 0 ? value : '';
        }
      },
      axisTick: { show: false }
    },
    series: series
  };

  deviationChartInstance.setOption(option);
};

// 新增: 更新纠偏状态图表函数
const updateDeviationChart = () => {
  if (!deviationChartInstance) return;

  const seriesNames = Object.keys(deviationData.seriesData);
  const legendData = seriesNames.filter(name => !name.startsWith('_'));

  const updatedSeries = seriesNames.map((name, index) => ({
    name: name,
    type: 'bar' as const,
    data: deviationData.seriesData[name as keyof typeof deviationData.seriesData],
    itemStyle: {
      color: deviationData.colors[index % deviationData.colors.length]
    },
    label: {
      //保留原有的label设置或根据需要调整
    },
    barWidth: '25%',
    legendHoverLink: !name.startsWith('_')
  }));

  deviationChartInstance.setOption({
    legend: { // 确保图例也得到更新，以防万一
      data: legendData,
      top: '5%',
      textStyle: { color: '#ffffff' }
    },
    yAxis: { // 确保Y轴类别也得到更新
      type: 'category',
      data: deviationData.categories,
      axisLine: { lineStyle: { color: '#3a71a8' } },
      axisLabel: {
        color: '#c0d8ff',
        fontSize: 11,
        formatter: (value: string, index: number) => {
          return index % 2 === 0 ? value : '';
        }
      },
      axisTick: { show: false }
    },
    series: updatedSeries
  }, { notMerge: false }); // 使用 notMerge: false 仅更新数据，保留其他配置
};

// --- Gauge Chart Initialization ---
const GaugeBaseOptions: { [key: string]: { max: number; title: string; segmentation1: number; segmentation2: number } } = {
  'gauge-entry': { max: 300, title: 'mpm', segmentation1: 80, segmentation2: 300 },
  'gauge-process': { max: 300, title: 'mpm', segmentation1: 120, segmentation2: 300 },
  'gauge-skinpass': { max: 300, title: 'mpm', segmentation1: 80, segmentation2: 300 },
  'gauge-welder': { max: 300, title: 'mpm', segmentation1: 80, segmentation2: 300 },
};

const initGaugeChart = (chartId: string, value: number) => {
  const chartDom = document.getElementById(chartId);
  if (!chartDom) {
    console.error(`Gauge chart DOM element not found: ${chartId}`);
    return null;
  }
  let gaugeChart = echarts.getInstanceByDom(chartDom);
  if (!gaugeChart) {
    gaugeChart = echarts.init(chartDom);
  }
  const baseOption = GaugeBaseOptions[chartId];
  if (!baseOption) {
    console.error(`No base options found for gauge: ${chartId}`);
    return null;
  }

  const option: EChartsOption = {
    series: [
      {
        type: 'gauge',
        center: ["50%", "50%"],
        radius: '95%',
        startAngle: 225,
        endAngle: -45,
        min: 0,
        max: baseOption.max,
        splitNumber: 5,
        progress: {
          show: true,
          roundCap: true,
          width: 6,
          itemStyle: { color: '#409EFF' }
        },
        axisLine: {
          roundCap: true,
          lineStyle: {
            width: 6,
            color: [
              [1, new echarts.graphic.LinearGradient(0, 1, 0.9, 1, [
                { offset: 0, color: "#D64444" },
                { offset: 0.2, color: "#D86E6D" },
                { offset: 0.5, color: "#F1F3F4" },
                { offset: 0.65, color: "#F1F3F4" },
                { offset: 0.8, color: "#79ACF6" },
                { offset: 1, color: "#1976FD" }
              ])]
            ] as any
          }
        },
        pointer: {
          length: '90%',
          width: 2,
          itemStyle: { color: '#ffffff' }
        },
        axisTick: {
          distance: -14,
          length: 2,
          lineStyle: { color: '#4B83F7', width: 2 }
        },
        anchor: {
          show: true,
          showAbove: true,
          size: 8,
          itemStyle: { borderColor: '#c0d8ff', borderWidth: 1, color: '#173164' }
        },
        splitLine: {
          distance: -16,
          length: 6,
          lineStyle: { color: '#4B83F7', width: 2 }
        },
        axisLabel: {
          color: '#FFF',
          fontSize: 14,
          distance: -30,
          rotate: 'tangential',
          formatter: function (value: any) {
            return (value !== 0 && value !== baseOption.segmentation1 && value !== baseOption.segmentation2 && value !== baseOption.max) ? '' : '';
          }
        },
        title: {
          offsetCenter: [0, '70%'],
          fontSize: 12,
          color: '#FFF',
        },
        detail: {
          fontSize: 18,
          offsetCenter: [0, '30%'],
          valueAnimation: true,
          formatter: (val: number) => val.toFixed(1),
          color: '#FFF'
        },
        data: [{ value: value, name: baseOption.title }]
      }
    ]
  };

  gaugeChart.setOption(option, true);
  return gaugeChart;
};

// --- Data Fetching and Processing Functions ---
const fetchData = async () => {
  try {
    const [zoneTrkRes, itemTagRes] = await Promise.all([
      axios.get('http://10.171.7.100:8090/restapi?name=TCM2280_zonetrk'),
      axios.get('http://10.171.7.100:8090/restapi?name=TCM2280_itemtag')
    ]);
    apiData.value = zoneTrkRes.data;
    itemTagData.value = itemTagRes.data;
  } catch (error) {
    console.error('请求失败:', error);
    if (axios.isAxiosError(error) && error.config?.url) {
      if (error.config.url.includes('_zonetrk')) apiData.value = null;
      if (error.config.url.includes('_itemtag')) itemTagData.value = null;
    } else {
      apiData.value = null;
      itemTagData.value = null;
    }
  }
};

const updateSimulationState = () => {
  if (apiData.value && apiData.value.zoneno) {
    const currentZoneCoils: { [key: string]: string | null } = {};
    const seenCoilIds = new Set<string>();
    const zoneKeys = Object.keys(apiData.value.zoneno).sort((a, b) => parseInt(a) - parseInt(b));

    // Process main zones first
    zoneKeys.forEach(zoneKey => {
      const zoneData = apiData.value.zoneno[zoneKey];
      const zoneId = `zone${zoneKey}`;
      if (zoneData.entId && zoneData.entId !== 'ENTIDBOOK' && zoneData.entId.trim() !== '') {
        currentZoneCoils[zoneId] = zoneData.entId;
        seenCoilIds.add(zoneData.entId);
      } else {
        currentZoneCoils[zoneId] = null;
      }
    });

    // Assign colors to coils
    const updatedColorMap = { ...coilColorMap.value };
    seenCoilIds.forEach(coilId => {
      if (!(coilId in updatedColorMap)) {
        updatedColorMap[coilId] = animationColors[nextColorIndex % animationColors.length];
        nextColorIndex++;
      }
    });
    coilColorMap.value = updatedColorMap;

    // Update Speeds
    if (apiData.value.speed && apiData.value.speed.length >= 4) {
      entrySpeed.value = parseFloat(apiData.value.speed[0] || '0');
      processSpeed.value = parseFloat(apiData.value.speed[1] || '0');
      skinpassSpeed.value = parseFloat(apiData.value.speed[2] || '0');
      welderSpeed.value = parseFloat(apiData.value.speed[3] || '0');
      gaugeEntryInstance?.setOption({ series: [{ data: [{ value: entrySpeed.value }] }] });
      gaugeProcessInstance?.setOption({ series: [{ data: [{ value: processSpeed.value }] }] });
      gaugeSkinpassInstance?.setOption({ series: [{ data: [{ value: skinpassSpeed.value }] }] });
      gaugeWelderInstance?.setOption({ series: [{ data: [{ value: welderSpeed.value }] }] });
    }

    // Update Loopers
    if (apiData.value.loop && apiData.value.loop.length >= 3) {
      const scaleFactor = 100 / 10000;
      inletLooperPercent.value = parseFloat(apiData.value.loop[0] || '0') * scaleFactor;
      middleLooperPercent.value = parseFloat(apiData.value.loop[1] || '0') * scaleFactor;
      exportLooperPercent.value = parseFloat(apiData.value.loop[2] || '0') * scaleFactor;
      looperData.entry.actual = inletLooperPercent.value;
      looperData.middle.actual = middleLooperPercent.value;
      looperData.exit.actual = exportLooperPercent.value;
      looperChartInstance?.setOption({
        series: [
          {
            name: '实际值',
            type: 'bar',
            data: [
              Math.round(looperData.entry.actual),
              Math.round(looperData.middle.actual),
              Math.round(looperData.exit.actual)
            ],
            // ...
          },
          {
            name: '标准值',
            type: 'bar',
            data: [
              Math.round(looperData.entry.standard),
              Math.round(looperData.middle.standard),
              Math.round(looperData.exit.standard)
            ],
            // ...
          }
        ]
      });
    }

    // Update Uncoiler Lengths from wplen
    try {
      if (apiData.value.por1CoilNo) {
        let found = false;
        for (const zoneKey in apiData.value.zoneno) {
          const zoneData = apiData.value.zoneno[zoneKey];
          if (zoneData.entId === apiData.value.por1CoilNo) {
            uncoiler1Length.value = parseFloat(zoneData.wplen || '0') / 1000;
            found = true;
            break;
          }
        }
        if (!found) uncoiler1Length.value = 0;
      } else { uncoiler1Length.value = 0; }
      if (apiData.value.por2CoilNo) {
        let found = false;
        for (const zoneKey in apiData.value.zoneno) {
          const zoneData = apiData.value.zoneno[zoneKey];
          if (zoneData.entId === apiData.value.por2CoilNo) {
            uncoiler2Length.value = parseFloat(zoneData.wplen || '0') / 1000;
            found = true;
            break;
          }
        }
        if (!found) uncoiler2Length.value = 0;
      } else { uncoiler2Length.value = 0; }
    } catch (e) {
      console.error("Error updating uncoiler lengths:", e);
      uncoiler1Length.value = 0; uncoiler2Length.value = 0;
    }

    // Propagate colors to connector paths
    let lastZoneCoilId: string | null = null;
    const finalPathIds = [
      'zone36', 'path222', 'zone35', 'zone34', 'zone33', 'zone32', 'zone31', 'zone30', 'zone29', 'path29', 'zone28', 'path28', 'zone27', 'path-27', 'zone26', 'path-26', 'zone25', 'path-45623', 'zone24', 'path-1775', 'zone23', 'zone22', 'path-55156', 'zone21', 'path-5478', 'zone20', 'path-55148', 'path-551423', 'zone19', 'path-5841', 'path-8524', 'zone18', 'path-5255', 'path-562', 'zone17', 'path-523', 'path-546', 'zone16', 'zone15', 'zone14', 'zone13', 'zone12', 'zone11', 'zone10', 'zone9', 'zone8', 'zone7', 'zone6', 'zone5', 'zone4', 'path666', 'zone3', 'path898', 'zone2', 'path111', 'zone1', 'zone0', 'zone_8_1-9', 'zone_8_2-81'
    ];
    console.log("Starting color propagation...");
    const propagatedZoneCoils: { [key: string]: string | null } = {};
    finalPathIds.forEach(id => {
      if (id.startsWith('zone')) {
        const directCoilId = currentZoneCoils[id];
        // Check if the zone has its own valid coil ID
        if (directCoilId && directCoilId !== 'ENTIDBOOK' && directCoilId.trim() !== '') {
          propagatedZoneCoils[id] = directCoilId;
          lastZoneCoilId = directCoilId; // Update last known coil ID
          console.log(`  Zone ${id}: Direct Coil=${directCoilId}, Last Zone Coil Updated=${lastZoneCoilId}`);
        } else {
          // Zone has no data, inherit from the previous segment
          propagatedZoneCoils[id] = lastZoneCoilId;
          console.log(`  Zone ${id}: Direct Coil=null/invalid, Inheriting Coil=${lastZoneCoilId}`);
          // Do NOT update lastZoneCoilId here
        }
      } else {
        // Path segment, always inherit
        propagatedZoneCoils[id] = lastZoneCoilId;
        console.log(`  Path ${id}: Inheriting Coil=${lastZoneCoilId}`);
      }
    });
    zoneCoilMap.value = propagatedZoneCoils;
    console.log("Finished color propagation. Final zoneCoilMap:", JSON.stringify(zoneCoilMap.value));

  } else {
    console.warn("_zonetrk data is not available.");
    zoneCoilMap.value = {};
    // Reset other relevant values
  }

  // Update remaining info boxes from _itemtag
  if (itemTagData.value) {
    try {
      coilerLength.value = parseFloat(itemTagData.value['L_TNR2_LENFB'] || '0') / 1000;
      thicknessDeviation.value = parseFloat(itemTagData.value['M_400_208NI_EXIT'] || '0');

      // Add log for mill entry speed tag
      const millSpeedTagValue = itemTagData.value['M_010_014DS_ANS'];
      console.log("Mill Entry Speed Tag Value:", millSpeedTagValue);
      millEntrySpeed.value = parseFloat(millSpeedTagValue || '0');

      // --- BEGIN: Update Deviation Chart Data ---
      const stripPositions: number[] = [];
      const cylinderPositions: number[] = [];
      const stripPosNegative: number[] = [];

      // categories are 'CPC1', 'CPC2', ..., 'CPC11'
      // Ensure itemTagData.value is not null before accessing its properties
      if (itemTagData.value) {
        for (let i = 0; i < deviationData.categories.length; i++) {
          const cpcNumber = i + 1;
          const stripPosKey = `L_CPC${cpcNumber}_STRPPOSFB`;
          const cylPosKey = `L_CPC${cpcNumber}_CYLPOSFB`;

          const stripPosValue = Number(parseFloat(itemTagData.value[stripPosKey] || '0').toFixed(2));
          const cylPosValue = Number(parseFloat(itemTagData.value[cylPosKey] || '0').toFixed(2));

          stripPositions.push(stripPosValue);
          cylinderPositions.push(cylPosValue);
          stripPosNegative.push(-stripPosValue); // Calculate negative of strip position
        }

        deviationData.seriesData.带钢位置 = stripPositions;
        deviationData.seriesData.油缸位置 = cylinderPositions;
        deviationData.seriesData._stripPosNegative = stripPosNegative; // Update _stripPosNegative

        // Call update function for deviation chart
        updateDeviationChart();
      }
      // --- END: Update Deviation Chart Data ---

    } catch (e) {
      console.error("Error processing itemTagData for info boxes or deviation chart:", e);
      coilerLength.value = 0;
      thicknessDeviation.value = 0;
      millEntrySpeed.value = 0;
      // Optionally reset deviation data on error
      // deviationData.seriesData.带钢位置 = deviationData.categories.map(() => 0);
      // deviationData.seriesData.油缸位置 = deviationData.categories.map(() => 0);
    }
  } else {
    coilerLength.value = 0;
    thicknessDeviation.value = 0;
    millEntrySpeed.value = 0;
  }
};

// --- SVG Animation Setup & Update Display ---
const setupSvgAnimation = () => {
  const container = svgContainerRef.value;
  if (!container) { console.error("SVG container not found!"); return; }
  // Ensure ALL relevant paths are included here in order
  const pathIdsToAnimate = [
    'zone36', 'path222', 'zone35', 'zone34', 'zone33', 'zone32', 'zone31', 'zone30', 'zone29', 'path29', 'zone28', 'path28', 'zone27', 'path-27', 'zone26', 'path-26', 'zone25', 'path-45623', 'zone24', 'path-1775', 'zone23', 'zone22', 'path-55156', 'zone21', 'path-5478', 'zone20', 'path-55148', 'path-551423', 'zone19', 'path-5841', 'path-8524', 'zone18', 'path-5255', 'path-562', 'zone17', 'path-523', 'path-546', 'zone16', 'zone15', 'zone14', 'zone13', 'zone12', 'zone11', 'zone10', 'zone9', 'zone8', 'zone7', 'zone6', 'zone5', 'zone4', 'path666', 'zone3', 'path898', 'zone2', 'path111', 'zone1', 'zone0', 'zone_8_1-9', 'zone_8_2-81'
    // Verify against SVG source if more paths are needed
  ];
  const segments: PathSegment[] = [];
  let currentCumulativeLength = 0;
  pathSegments.value = [];
  for (const id of pathIdsToAnimate) {
    let originalPath = container.querySelector(`#${id}`) as SVGPathElement | null;
    if (!originalPath) originalPath = container.querySelector(`path[id="${id}"]`) as SVGPathElement | null;
    if (originalPath && originalPath instanceof SVGPathElement) {
      const length = originalPath.getTotalLength();
      // Allow zero length only for zones, maybe? Connectors MUST have length.
      if (length === 0 && !id.startsWith('zone')) {
        console.warn(`Connector path ${id} has zero length, skipping.`);
        continue;
      }
      currentCumulativeLength += length;
      if (originalPath.style.stroke !== 'none') {
        originalPath.style.stroke = 'rgba(255, 255, 255, 0.1)';
        originalPath.style.strokeWidth = '1px';
      }
      const pathClone = originalPath.cloneNode(true) as SVGPathElement;
      pathClone.id = `clone-${id}`;
      pathClone.style.stroke = 'transparent';
      pathClone.style.strokeWidth = '1px';
      pathClone.style.fill = 'none';
      pathClone.style.strokeDasharray = `${length} 0`;
      pathClone.style.strokeDashoffset = '0';
      pathClone.style.display = '';
      originalPath.parentNode?.appendChild(pathClone);
      segments.push({ id, originalElement: originalPath, pathClone, length, cumulativeLength: currentCumulativeLength });
    } else {
      console.warn(`Path element not found or not an SVGPathElement for ID: ${id}`);
    }
  }
  if (segments.length > 0) {
    pathSegments.value = segments;
    totalPathLength.value = currentCumulativeLength;
    console.log("SVG Animation Setup Complete. Segments:", pathSegments.value.length);
    updateAnimationDisplay(); // Initial display update
  } else {
    console.error("No valid path segments found for animation.");
  }
};

const updateAnimationDisplay = () => { // Simple display update based on map
  if (pathSegments.value.length === 0) return;
  for (const segment of pathSegments.value) {
    const id = segment.id;
    const coilId = zoneCoilMap.value[id]; // Check map for this specific ID
    if (coilId && coilId !== 'ENTIDBOOK') {
      const color = coilColorMap.value[coilId] || '#808080';
      segment.pathClone.style.stroke = color;
      segment.pathClone.style.opacity = '1';
    } else {
      segment.pathClone.style.stroke = 'transparent';
      segment.pathClone.style.opacity = '0';
    }
  }
};

// --- Chart Initialization & Disposal ---
const initCharts = () => {
  disposeCharts();

  if (looperChartRef.value) {
    looperChartInstance = echarts.init(looperChartRef.value);
    const option: EChartsOption = {
      ...getBaseChartOption(),
      grid: { left: '20%', right: '10%', top: '15%', bottom: '10%' },
      legend: { data: ['实际值', '标准值'], top: '5%', right: '10%', textStyle: { color: '#ffffff' } },
      xAxis: { type: 'value', axisLabel: { show: false }, splitLine: { show: true, lineStyle: { color: '#3a71a8', type: 'dashed', opacity: 0.2 } } },
      yAxis: { type: 'category', data: ['入口', '中间', '出口'], axisLine: { lineStyle: { color: '#3a71a8' } }, axisLabel: { color: '#c0d8ff', fontSize: 11 }, axisTick: { show: false } },
      series: [
        { name: '实际值', type: 'bar', data: [looperData.entry.actual, looperData.middle.actual, looperData.exit.actual], itemStyle: { color: '#409EFF' }, barWidth: '30%', z: 10, label: { show: true, position: 'right', color: '#ffffff', fontSize: 10 } },
        { name: '标准值', type: 'bar', data: [looperData.entry.standard, looperData.middle.standard, looperData.exit.standard], itemStyle: { color: 'rgba(64, 158, 255, 0.3)' }, barWidth: '30%', barGap: '-100%' }
      ]
    };
    looperChartInstance.setOption(option);
  }

  if (teamOperationChartRef.value) {
    teamOperationChartInstance = echarts.init(teamOperationChartRef.value);
    updateTeamOperationChart();
  }

  if (deviationChartRef.value) {
    initDeviationChart();
  }

  gaugeEntryInstance = initGaugeChart("gauge-entry", entrySpeed.value);
  gaugeProcessInstance = initGaugeChart("gauge-process", processSpeed.value);
  gaugeSkinpassInstance = initGaugeChart("gauge-skinpass", skinpassSpeed.value);
  gaugeWelderInstance = initGaugeChart("gauge-welder", welderSpeed.value);
};

const disposeCharts = () => {
  looperChartInstance?.dispose();
  teamOperationChartInstance?.dispose();
  gaugeEntryInstance?.dispose();
  gaugeProcessInstance?.dispose();
  gaugeSkinpassInstance?.dispose();
  gaugeWelderInstance?.dispose();
  deviationChartInstance?.dispose();
  looperChartInstance = null;
  teamOperationChartInstance = null;
  gaugeEntryInstance = null;
  gaugeProcessInstance = null;
  gaugeSkinpassInstance = null;
  gaugeWelderInstance = null;
  deviationChartInstance = null;
};

const handleResize = () => {
  looperChartInstance?.resize();
  teamOperationChartInstance?.resize();
  gaugeEntryInstance?.resize();
  gaugeProcessInstance?.resize();
  gaugeSkinpassInstance?.resize();
  gaugeWelderInstance?.resize();
  deviationChartInstance?.resize();
};

// --- Lifecycle Hooks & Watchers ---
watch([apiData, itemTagData], ([newApiData, newItemTagData]) => {
  console.log("newItemTagData", newItemTagData);
  if (newApiData || newItemTagData) { // Modified to also react if only itemTagData changes
    updateSimulationState();
  }
}, { deep: true });

watch([zoneCoilMap, coilColorMap], () => {
  updateAnimationDisplay();
}, { deep: true });

onMounted(() => {
  nextTick(() => {
    initCharts();
    setupSvgAnimation(); // Does not start animation loop now
    fetchData(); // Initial fetch for _zonetrk
  });
  if (fetchDataIntervalId.value === null) {
    fetchDataIntervalId.value = window.setInterval(fetchData, 3000);
  }
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  disposeCharts();
  if (fetchDataIntervalId.value !== null) {
    clearInterval(fetchDataIntervalId.value);
    fetchDataIntervalId.value = null;
  }
});
</script>

<style scoped>
/* --- Base & Layout --- */
.arpe-container {
  height: 100vh;
  width: 100%;
  background: url('../../assets/images/body-bg.jpg') no-repeat center center;
  background-size: cover;
  color: #fff;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.arpe-header {
  flex: 0 0 60px;
  background-image: url('../../assets/images/head-bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 5px;
  z-index: 10;
}

.arpe-title {
  font-size: 22px;
  color: #ffffff;
  text-align: center;
  letter-spacing: 2px;
}

.arpe-main-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 10px;
  overflow: hidden;
  margin-top: -30px;
}

/* --- SVG Card --- */
.svg-card {
  flex: 0 0 45%;
  min-height: 180px;
  background-color: rgba(28, 58, 99, 0.7);
  border: 1px solid rgba(90, 130, 190, 0.4);
  box-shadow: 0 0 10px rgba(11, 93, 209, 0.15);
  border-radius: 2px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.svg-card> :deep(.containerContent) {
  flex-grow: 1;
  padding: 0;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.svg-card-content-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.svg-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
}

.svg-container> :deep(svg) {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: contain;
  overflow: visible !important;
}

/* --- Bottom Grid Layout --- */
.arpe-bottom-grid {
  flex-grow: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  overflow: hidden;
  margin-top: -5px;
  position: relative;
  z-index: 5;
}

/* Base style for the main columns (left and right) */
.arpe-bottom-column {
  display: grid;
  /* Use grid for stacking/containing */
  gap: 10px;
  overflow: hidden;
  /* Define rows for the right column to position elements */
}

.arpe-bottom-grid>.arpe-bottom-column:nth-child(2) {
  /* Target right column */
  grid-template-rows: 1fr 1fr;
  /* Give equal height to top (tables) and bottom (chart) rows */
}

/* New rule for the horizontal wrapper WITHIN the left column */
.left-column-content-wrapper {
  display: flex;
  flex-direction: row;
  gap: 10px;
  height: 100%;
  /* Fill the grid cell */
  width: 100%;
}

/* Cards within the horizontal wrapper (left column) */
.left-column-content-wrapper>.chart-card {
  flex: 1;
  /* Equal width split */
  min-width: 0;
  /* Card itself is a flex column already via generic styles */
}

/* Ensure content within these specific cards grows */
.left-column-content-wrapper>.chart-card> :deep(.containerContent) {
  flex-grow: 1;
  overflow: hidden;
  padding: 5px;
  position: relative;
  display: flex;
  flex-direction: column;
}

.left-column-content-wrapper>.chart-card> :deep(.containerContent) .arpe-chart,
.left-column-content-wrapper>.chart-card> :deep(.containerContent)>div {
  /* Target placeholder div too */
  flex-grow: 1;
}

/* --- Generic Card Styles --- */
.chart-card,
.table-card {
  background-color: rgba(28, 58, 99, 0.7);
  border: 1px solid rgba(90, 130, 190, 0.4);
  box-shadow: 0 0 10px rgba(11, 93, 209, 0.15);
  border-radius: 2px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Content within vertical cards */
.arpe-bottom-column>.chart-card> :deep(.containerContent),
.arpe-bottom-column>.table-card> :deep(.containerContent) {
  flex-grow: 1;
  padding: 5px;
  overflow: hidden;
  position: relative;
}

/* Restored rule for the horizontal wrapper for tables in the right column */
.arpe-bottom-column-horizontal {
  display: flex;
  flex-direction: row;
  gap: 10px;
  overflow: hidden;
}

/* Content within horizontal cards */
.arpe-bottom-column-horizontal>.table-card {
  flex: 1;
  min-width: 0;
}

.arpe-bottom-column-horizontal>.table-card> :deep(.containerContent) {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  padding: 5px;
  overflow: hidden;
  position: relative;
}

/* Horizontal table container needs explicit flex grow */
.arpe-bottom-column-horizontal>.table-card> :deep(.containerContent) .table-container {
  flex-grow: 1;
}

.arpe-chart {
  flex-grow: 1;
  min-height: 100px;
}

/* --- Table Styles --- */
.table-container {
  height: 100%;
  width: 100%;
  overflow: hidden;
}

/* Deep styles for ElTable */
:deep(.el-table) {
  background-color: transparent !important;
  border: none !important;
}

:deep(.el-table tr:nth-child(odd)) {
  background-color: #0f2142 !important;
}

:deep(.el-table tr:nth-child(even)) {
  background-color: #142a52 !important;
}

:deep(.el-table th.el-table__cell) {
  background-color: #183272 !important;
  color: #b8e8ff !important;
  border-bottom: 1px solid #06279d !important;
  padding: 4px 0;
  font-size: 12px;
  font-weight: normal;
  text-align: center;
}

:deep(.el-table td.el-table__cell) {
  background-color: transparent !important;
  color: #c0c4cc !important;
  border-bottom: 1px solid #06279d !important;
  border-right: 1px solid #06279d !important;
  padding: 4px 0;
  font-size: 12px;
  text-align: center;
}

:deep(.el-table td.el-table__cell:first-child),
:deep(.el-table th.el-table__cell:first-child) {
  border-left: none !important;
}

:deep(.el-table td.el-table__cell:last-child),
:deep(.el-table th.el-table__cell:last-child) {
  border-right: none !important;
}

:deep(.el-table--border .el-table__inner-wrapper::after),
:deep(.el-table--border::after),
:deep(.el-table--border::before),
:deep(.el-table__inner-wrapper::before) {
  background-color: #06279d !important;
}

:deep(.el-table .el-table__border-left-patch),
:deep(.el-table .el-table__border-right-patch) {
  background-color: #06279d !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  background-color: inherit !important;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar) {
  width: 4px;
  height: 4px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-track) {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background-color: rgba(58, 113, 168, 0.5);
  border-radius: 2px;
}

:deep(.el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background-color: rgba(58, 113, 168, 0.8);
}

/* --- Key Parameters Card --- */
.key-params-card> :deep(.containerContent) {
  padding: 5px;
}

:deep(.key-params-card .header-radio-group .el-radio-button__inner) {
  background-color: rgba(20, 50, 100, 0.6);
  border: 1px solid #3a71a8 !important;
  color: #a2dfff;
  box-shadow: none;
  padding: 3px 8px;
  font-size: 12px;
  border-left: 0 !important;
}

:deep(.key-params-card .header-radio-group .el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid #3a71a8 !important;
  border-radius: 3px 0 0 3px;
}

:deep(.key-params-card .header-radio-group .el-radio-button:last-child .el-radio-button__inner) {
  border-radius: 0 3px 3px 0;
}

:deep(.key-params-card .header-radio-group .el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background-color: #409EFF;
  border-color: #409EFF !important;
  color: #ffffff;
  box-shadow: none;
}

:deep(.key-params-card .header-radio-group .el-radio-button__inner:hover) {
  color: #ffffff;
  background-color: rgba(64, 158, 255, 0.5);
}

/* --- Gauges & Info Boxes --- */
.gauge-container {
  position: absolute;
  z-index: 10;
  width: 100px;
  height: 65px;
}

.gauge-entry {
  left: 10%;
  bottom: 2%;
}

.gauge-process {
  left: 30%;
  bottom: 2%;
}

.gauge-skinpass {
  left: 63%;
  bottom: 2%;
}

.gauge-welder {
  left: 80%;
  bottom: 2%;
}

.semitransp_box {
  position: absolute;
  border-radius: 4px;
  background: rgba(6, 62, 144, 0.75);
  border: 1px solid rgba(58, 113, 168, 0.6);
  width: fit-content;
  min-width: 80px;
  padding: 1px 4px;
  font-weight: normal;
  text-align: center;
  color: #c0d8ff;
  font-size: 10px;
  z-index: 10;
  line-height: 1.2;
}

.semitransp_box p {
  margin: 0;
  white-space: nowrap;
}

.info-coiler {
  left: 1.5%;
  top: 40%;
}

.info-thickness-deviation {
  left: 1.5%;
  top: 30%;
}

.info-yibiao1 {
  left: 80.7%;
  top: 68%;
}

.info-yibiao2 {
  left: 63.6%;
  top: 68%;
}

.info-inlet-looper-val {
  left: 17%;
  top: 15%;
}

.info-inlet-looper-time {
  left: 17%;
  top: 25%;
}

.info-middle-looper-val {
  left: 42%;
  top: 12%;
}

.info-middle-looper-time {
  left: 58%;
  top: 12%;
}

.info-export-looper-val {
  left: 75%;
  top: 15%;
}

.info-export-looper-time {
  left: 75%;
  top: 25%;
}

.info-uncoiler1 {
  right: 1%;
  top: 12%;
}

.info-uncoiler2 {
  right: 2%;
  top: 72%;
}

/* --- Alarm Banner --- */
.alarm-banner {
  position: absolute;
  top: 5px;
  left: 10px;
  z-index: 15;
  background-image: url('../../assets/img/red-warning.png');
  background-color: rgba(200, 60, 60, 0.85);
  background-size: cover;
  background-repeat: no-repeat;
  color: #fff;
  padding: 3px 10px;
  font-size: 12px;
  border: 1px solid #c83c3c;
  border-radius: 3px;
  box-shadow: 0 0 8px rgba(200, 60, 60, 0.5);
  white-space: nowrap;
  opacity: 0.8;
}

/* --- 新增: 小时吨钢状态框样式 (模仿 XGRPH) --- */
.arpe-status-box {
  position: absolute;
  /* 使用绝对定位 */
  z-index: 10;
  background-image: url('../../assets/img/videoicon.png');
  /* 沿用背景图 */
  background-size: 100% 100%;
  background-repeat: no-repeat;
  padding: 5px 8px;
  /* 调整内边距 */
  text-align: center;
  color: #fff;
  min-width: 90px;
  /* 调整宽度 */
  height: 55px;
  /* 调整高度 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* 底部装饰线 */
.arpe-status-box::before {
  content: '';
  position: absolute;
  bottom: 3px;
  /* 调整位置 */
  left: 25%;
  right: 25%;
  height: 1px;
  background: linear-gradient(90deg, transparent, #42b4ff, transparent);
  opacity: 0.6;
}

.arpe-status-box-label {
  font-size: 10px;
  /* 调整字体大小 */
  color: #a2cfff;
  margin-bottom: 2px;
  /* 调整间距 */
}

.arpe-status-box-value {
  font-size: 16px;
  /* 调整字体大小 */
  font-weight: bold;
  color: #fff;
  line-height: 1.1;
  text-shadow: 0 0 4px rgba(66, 180, 255, 0.7);
  margin-bottom: 14px;
}

.arpe-status-box-value span {
  font-size: 9px;
  /* 调整单位字体大小 */
  margin-left: 2px;
  opacity: 0.8;
}

/* 定位新增的状态框 */
.hourly-output {
  left: 24%;
  /* 移到目标区域 */
  top: 10%;
  /* 移到目标区域 */
}

.realtime-hourly-output {
  left: 34%;
  /* 与上一个对齐 */
  top: 10%;
  /* 放在上一个下方，留出间隙 */
}

/* --- 新增: 产量完成率样式 --- */
.production-completion-rate {
  position: absolute;
  z-index: 10;
  width: 150px;
  /* 根据背景图调整 */
  height: 150px;
  /* 根据背景图调整 */
  background-image: url('../../assets/img/zl-pic5.png');
  background-size: contain;
  /* 适应容器 */
  background-repeat: no-repeat;
  background-position: center center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  color: #fff;
  /* 定位到红框区域 (需要根据实际效果微调) */
  left: 50%;
  top: 85%;
  transform: translate(-50%, -50%);
  /* 使用 transform 精确居中 */
}

.completion-rate-value {
  font-size: 22px;
  /* 调整字体大小 */
  font-weight: bold;
  color: #00eaff;
  /* 青色 */
  line-height: 1.2;
  text-shadow: 0 0 5px rgba(0, 234, 255, 0.8);
  margin-top: 10px;
  /* 根据背景图微调 */
}

.completion-rate-label {
  font-size: 14px;
  color: #ffffff;
  margin-top: 5px;
  /* 调整间距 */
  margin-bottom: 55px;
}

/* Adjust positioning for mill entry speed */
.info-mill-entry-speed {
  position: absolute;
  /* Fine-tune based on reference image (near WD4/BR7) */
  left: 18%;
  /* Adjusted */
  top: 65%;
  /* Adjusted */
  z-index: 11;
  /* Increased z-index */
}

/* --- 新增: AI 速度卡片样式 --- */
.ai-speed-box {
  position: absolute;
  border-radius: 3px;
  background: linear-gradient(135deg, rgba(10, 25, 50, 0.85) 0%, rgba(15, 30, 60, 0.95) 100%);
  border: 1px solid #00ffff;
  /* Cyan border */
  box-shadow: 0 0 5px rgba(0, 255, 255, 0.5), inset 0 0 3px rgba(0, 255, 255, 0.3);
  width: fit-content;
  min-width: 110px;
  /* Adjusted min-width for longer text */
  padding: 2px 5px;
  text-align: center;
  color: #e0fcff;
  /* Light cyan text */
  font-size: 9px;
  /* Slightly smaller font for a denser look */
  z-index: 12;
  /* Ensure it's above other elements if overlapping */
  line-height: 1.3;
  font-family: 'Consolas', 'Lucida Console', monospace;
  /* Monospace font for tech feel */
}

.ai-speed-box p {
  margin: 0;
  white-space: nowrap;
  text-shadow: 0 0 3px rgba(0, 200, 200, 0.7);
}

/* Tentative positioning for new AI speed boxes */
.info-ai-entry-speed {
  right: 9%;
  top: 10%;
}

.info-ai-process-speed {
  right: 44%;
  top: 10%;
}

.info-ai-exit-speed {
  left: 8%;
  top: 10%;
}
</style>
